package com.linkage.jz.bankruptcy.fragment.Project;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aspsine.swipetoloadlayout.OnLoadMoreListener;
import com.aspsine.swipetoloadlayout.OnRefreshListener;
import com.aspsine.swipetoloadlayout.SwipeToLoadLayout;
import com.google.gson.Gson;
import com.linkage.jz.bankruptcy.BankruptcyApp;
import com.linkage.jz.bankruptcy.Consts;
import com.linkage.jz.bankruptcy.R;
import com.linkage.jz.bankruptcy.activity.Project.CreateProjectDetailThreeActivity;
import com.linkage.jz.bankruptcy.activity.Project.SelZQUserListActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.AddProxyUserActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUser.ZQUserZQShowDetailActivity;
import com.linkage.jz.bankruptcy.activity.Project.ZQUserListActivity;
import com.linkage.jz.bankruptcy.adapter.ProZQUserConfirmListViewAdapter;
import com.linkage.jz.bankruptcy.adapter.ProZQUserConfirmToBeListViewAdapter;
import com.linkage.jz.bankruptcy.bean.ZQUserDetailAuthBaseInfo;
import com.linkage.jz.bankruptcy.bean.ZQUserInfo;
import com.linkage.jz.bankruptcy.event.RefreshEvent;
import com.linkage.jz.bankruptcy.net.ToastUtil;
import com.linkage.jz.bankruptcy.utils.SPUtils;
import com.linkage.jz.bankruptcy.utils.Utils;
import com.linkage.jz.bankruptcy.widget.CreateUserDialog;
import com.linkage.jz.bankruptcy.widget.CreateZQUserDialog;
import com.linkage.jz.bankruptcy.widget.Divider;
import com.linkage.jz.bankruptcy.widget.PublicNoticeDialog;
import com.linkage.jz.bankruptcy.widget.ShapeLoadingDialog;
import com.linkage.seapeak.activity.chat.ChatDetailActivity;
import com.linkage.seapeak.base.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnItemChildLongClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemLongClickListener;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.chad.library.adapter.base.listener.SimpleClickListener.TAG;


/**
 * date : 2016/5/24
 * author : lijiawei
 */
public class ZQUserToBeConfirmListFrgment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener, BGAOnRVItemClickListener, BGAOnRVItemLongClickListener, BGAOnItemChildClickListener, BGAOnItemChildLongClickListener {

    //显示信息
    private TextView tv_total;
    private LinearLayout ll_total;
    private RelativeLayout rl_search;
    //    private static final String TAG = RecyclerViewDemoActivity.class.getSimpleName();
    private ProZQUserConfirmToBeListViewAdapter mAdapter;
    private ArrayList<ZQUserInfo> mData;
    private RecyclerView mDataRv;
//    private EditText law_searchtxt;
    private TextView law_searchtxt;
    SwipeToLoadLayout mSwipeToLoadLayout;
    private String mProID;
    private String managerFlag;
    private ShapeLoadingDialog shapeLoadingDialog ;
    private int curProcess =0;
    private LinearLayout ll_nodata;
    private Button btn_add_zq;
    private ZQUserDetailAuthBaseInfo mAuthBaseInfo;
    String arrayNum0 = "0";
    String arrayNum1 = "0";
    String arrayNum2 = "0";
    String arrayNum3 = "0";
    String arrayNum4 = "0";
    private String isOpen;


    private ArrayList<ZQUserInfo> mData1 = new ArrayList<>();
    private ArrayList<ZQUserInfo> mData2= new ArrayList<>();
    private ArrayList<ZQUserInfo> mData3= new ArrayList<>();
    private ArrayList<ZQUserInfo> mData4= new ArrayList<>();
    private ArrayList<ZQUserInfo> mData5= new ArrayList<>();

    private int page1 = 1;
    private int page2 = 1;
    private int page3 = 1;
    private int page4 = 1;
    private int page5 = 1;


    private CreateUserDialog createUserDialog;
    private CreateZQUserDialog createZQUserDialog;
    ArrayList<Fragment> fragments = new ArrayList<Fragment>();


    private String groupid;

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_zqusertobeconfirm_list, container, false);
        return view;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        initRecyclerView(view);
        EventBus.getDefault().register(this);
        shapeLoadingDialog = new ShapeLoadingDialog(getActivity());
        Bundle bundle =this.getArguments();//得到从Activity传来的数据

        if(bundle!=null){
            mProID = bundle.getString("proid");
            managerFlag = bundle.getString("managerFlag");
            isOpen = bundle.getString("openAuth");
        }

//        getData();


    }

    PublicNoticeDialog noticeDialog;
    private void init(View view) {
//        text = (TextView) view.findViewById(R.id.fragment_textview);
//        text.setText("GroupChildrenHasBuy");
        ll_nodata = (LinearLayout)view.findViewById(R.id.ll_nodata);
        btn_add_zq = (Button)view.findViewById(R.id.btn_add_zq);
        tv_total = (TextView)view.findViewById(R.id.tv_total);
        ll_total = (LinearLayout)view.findViewById(R.id.ll_total);


        btn_add_zq.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                createZQUserDialog = new CreateZQUserDialog(getActivity(), onClickListener);
//                createUserDialog.show();

                ((ZQUserListActivity)getActivity()).showAddZQUser();
//                EventBus.getDefault().post(RefreshEvent.ADDZQUSRFLOW);
            }
        });
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshEvent event) {
        if (TextUtils.equals(event.getType(), RefreshEvent.TYPE_ZQUSRE_LIST)) {
            getData();
        }
    }

    private void initRecyclerView(final View view) {

        mDataRv = (RecyclerView) view.findViewById(R.id.rv_recyclerview_data);
//        mDataRv.addItemDecoration(new Divider(getActivity()));
        law_searchtxt = (TextView) view.findViewById(R.id.law_searchtxt);
        mSwipeToLoadLayout = (SwipeToLoadLayout)view.findViewById(R.id.swipeToLoadLayout);
        rl_search = (RelativeLayout)view.findViewById(R.id.rl_search);
        mSwipeToLoadLayout.setTargetView(mDataRv);
        mSwipeToLoadLayout.setRefreshHeaderView(LayoutInflater.from(getActivity()).inflate(R.layout.layout_twitter_header, mSwipeToLoadLayout, false));
        /*设置上拉加载更多布局*/
        mSwipeToLoadLayout.setLoadMoreFooterView(LayoutInflater.from(getActivity()).inflate(R.layout.layout_classic_footer, mSwipeToLoadLayout, false));

        mSwipeToLoadLayout.setOnRefreshListener(this);
        mSwipeToLoadLayout.setOnLoadMoreListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    if (!ViewCompat.canScrollVertically(recyclerView, 1)) {
                        mSwipeToLoadLayout.setLoadingMore(true);
                    }
                }
            }
        });



        law_searchtxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SelZQUserListActivity.start(getActivity(),mProID,isOpen);
            }
        });


//        law_searchtxt.setOnEditorActionListener(new TextView.OnEditorActionListener(){
//            @Override
//
//            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
//
//// TODO Auto-generated method stub
//
//                if(arg1 == EditorInfo.IME_ACTION_SEARCH)
//
//                {
//                    InputMethodManager imm = (InputMethodManager) view.getContext()
//                            .getSystemService(Context.INPUT_METHOD_SERVICE);
//                    if (imm != null) {
//                        imm.hideSoftInputFromWindow(view.getWindowToken(),0);
//                    }
//                    mData.clear();
//                                mAdapter.notifyDataSetChanged();
//
//                    getData();
////                    Toast.makeText(AddMemberActivity.this,"呵呵",Toast.LENGTH_SHORT).show();
//
//// search pressed and perform your functionality.
//
//                }
//
//                return false;
//
//            }
//
//        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mDataRv.setLayoutManager(layoutManager);

        mAdapter = new ProZQUserConfirmToBeListViewAdapter(mDataRv,getActivity());
        mAdapter.setOnRVItemClickListener(this);
        mAdapter.setOnRVItemLongClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.setOnItemChildLongClickListener(this);

        mDataRv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                if (RecyclerView.SCROLL_STATE_DRAGGING == newState) {
                    mAdapter.closeOpenedSwipeItemLayoutWithAnim();
                }
            }
        });
        mData = new ArrayList<ZQUserInfo>();
        mAdapter.setData(mData);
        mDataRv.setAdapter(mAdapter);
    }
    private Handler mHandler = new Handler();
    @Override
    public void onRefresh() {
//        LogT.i("正在刷新:");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getData();
                mSwipeToLoadLayout.setRefreshing(false);
            }
        }, 2000);
    }

    @Override
    public void onLoadMore() {
//        LogT.i("加载更多数据:");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                getMoreData();
                mSwipeToLoadLayout.setLoadingMore(false);
            }
        }, 2000);
    }
    @Override
    public void onItemChildClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {
             ZQUserInfo info ;
                if(curProcess == 0)
                {
                    info = mData1.get(position-1);
                }else{
                    info= mData2.get(position-2);
                }
            mAdapter.closeOpenedSwipeItemLayoutWithAnim();
//            mAdapter.removeItem(position);
            noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (v.getId() == R.id.btn_save_notice) {
//                        AddProxyUserActivity.super.finish();
                        delUser(info.getId());
                    }
                    noticeDialog.dismiss();
                }
            }, 1, "提示", "确定删除？",
                    "取消", "确认");
            noticeDialog.show();

        }

        if(childView.getId() == R.id.tv_item_bgaswipe_status)
        {
//            Toast.makeText(getActivity(), "11111", Toast.LENGTH_SHORT).show();

            final ZQUserInfo info  =  mData1.get(position-1);
            noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener() {
                @Override
                public void onClick( View view ) {
                    String  sendStatus = "";
                    if (view.getId() == R.id.btn_chancel_notice) {//暂存
                        sendStatus = "1";
                        noticeDialog.dismiss();
                    } else if (view.getId() == R.id.ll_close) {
                        if (noticeDialog != null && noticeDialog.isShowing())
                            noticeDialog.dismiss();
                        return;
                    } else {//生成
                        sendStatus = "2";
                        noticeDialog.dismiss();
                        mailNoticeDone(info.getId());
                    }
//                    saveData(sendStatus);
                    noticeDialog.dismiss();

                }
            }, 1, "提示", "是否已邮寄通知该债权人？", "取消", "已通知");
            noticeDialog.show();

        }
        ZQUserInfo infoTmp = mAdapter.getItem(position);
        if (childView.getId() == R.id.iv_email) {
            if (infoTmp.getId() != null)

                ChatDetailActivity.start(getActivity(), infoTmp.getId(),
                        infoTmp.getCreditorName(), infoTmp.getBankruptcyProjectId());
        }

        if (childView.getId() == R.id.iv_email) {
            if(mAuthBaseInfo!=null )
            {
//                mAuthBaseInfo
                if(!mAuthBaseInfo.isContactCreditor())
                {
                    ToastUtil.showShort("您没有权限操作");
                    return;
                }
            }
            if (infoTmp.getId() != null)
                ChatDetailActivity.start(getActivity(), infoTmp.getId(),
                        infoTmp.getCreditorName(), infoTmp.getBankruptcyProjectId());
        }

        if (childView.getId() == R.id.iv_phone) {
            if(mAuthBaseInfo!=null )
            {
//                mAuthBaseInfo
                if(!mAuthBaseInfo.isContactCreditor())
                {
                    ToastUtil.showShort("您没有权限操作");
                    return;
                }
            }
            if (infoTmp != null || !TextUtils.isEmpty(infoTmp.getContact())) {

                final String phone = infoTmp.getContact();
                SetPhone(phone);
                noticeDialog = new PublicNoticeDialog(getActivity(), new View.OnClickListener(){

                    @Override
                    public void onClick(View v) {
                        switch (v.getId()) {
                            case R.id.ll_close:
                                noticeDialog.dismiss();
                                break;
                            case R.id.btn_chancel_notice:

                                if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_SMS_PERMISSION)){

                                    try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                        Intent intent = new Intent(Intent.ACTION_SENDTO);
                                        Uri data = Uri.parse("smsto:" + phone);
                                        intent.setData(data);
                                        startActivity(intent);

//                                                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:"+phoneNumber));
//                                                intent.putExtra("sms_body", message);
//                                                startActivity(intent);

                                    }catch (Exception ex){
                                        ex.printStackTrace();
                                    }
                                }
                                noticeDialog.dismiss();
                                break;

                            case R.id.btn_save_notice:
                                if(!"".equalsIgnoreCase(phone)) {
                                    if(checkReadPermission(Manifest.permission.CALL_PHONE,REQUEST_CALL_PERMISSION)){

                                        try {
//                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(phone));

                                            Intent intent = new Intent(Intent.ACTION_CALL);
                                            Uri data = Uri.parse("tel:" + phone);
                                            intent.setData(data);
                                            startActivity(intent);
                                        }catch (Exception ex){
                                            ex.printStackTrace();
                                        }
                                    }
                                }
                                noticeDialog.dismiss();

                                break;
                        }
                    }
                }, 2,phone, phone,"发短信","拨打电话");
                noticeDialog.show();
            } else
                showToast("无法获取号码");
        }
    }

    @Override
    public boolean onItemChildLongClick(ViewGroup parent, View childView, int position) {
        if (childView.getId() == R.id.tv_item_bgaswipe_delete) {

            return true;
        }
        if(childView.getId() == R.id.tv_item_bgaswipe_edit) {

            return true;
        }


        return false;
    }

    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            switch (v.getId()) {

                case R.id.btn_chancel_u:
                    createUserDialog.dismiss();
                    break;
                case R.id.btn_save_u:
                    String name = createUserDialog.text_name_u.getText().toString().trim();
                    String phone = createUserDialog.text_mobile_u.getText().toString().trim();
                    addUser(groupid,name,phone);
                    break;
                case R.id.btn_add_zq:
                    break;
            }
        }
    };


    @Override
    public void onRVItemClick(ViewGroup parent, View itemView, int position) {
        if(position>mAdapter.getItemCount()||position==mAdapter.getItemCount())
        {
            return;
        }
        ZQUserInfo model = mAdapter.getItem(position);
        if(model !=null) {

            if(model.getCurType()==1)
            {
                if("true".equalsIgnoreCase(managerFlag)) {
                    if("true".equalsIgnoreCase(isOpen)) {
                        Intent intent = new Intent(getActivity(), ZQUserDetailActivity.class);
                        intent.putExtra("creditorId", model.getId());
                        intent.putExtra("proid", mProID);
                        getActivity().startActivity(intent);
                    }
                }else{
//                    Intent intent = new Intent(getActivity(), ZQUserZQShowDetailActivity.class);
//                    intent.putExtra("creditorId", model.getId());
//                    intent.putExtra("proid", mProID);
//                    getActivity().startActivity(intent);
                    if("true".equalsIgnoreCase(isOpen)) {
                        ZQUserZQShowDetailActivity.start(getActivity(), model);
                    }
                }
            }else{
                int count = Integer.parseInt(model.getProcessStatus());
                Boolean flag = model.getShowListFlag();
                flag = !flag;

                showList(count,flag);

            }


        }

    }


    private void showList(int type,boolean show)
    {


        curProcess = type;
        List<ZQUserInfo> list0 = new ArrayList<>();
        mData.clear();
        if("true".equalsIgnoreCase(managerFlag)) {
            ZQUserInfo infoTmp0 = new ZQUserInfo();
            infoTmp0.setCurType(2);
            infoTmp0.setProcessStatus("0");
            infoTmp0.setShowListFlag(type == 0 ? show : false);
            infoTmp0.setGroupnum(Integer.parseInt(arrayNum0));
            mData.add(infoTmp0);
            if (type == 0 && show) {
                mData.addAll(mData1);
            }

            ZQUserInfo infoTmp1 = new ZQUserInfo();
            infoTmp1.setCurType(2);
            infoTmp1.setShowListFlag(type == 1 ? show : false);
            infoTmp1.setProcessStatus("1");
            infoTmp1.setGroupnum(Integer.parseInt(arrayNum1));
            mData.add(infoTmp1);
            if (type == 1 && show) {
                mData.addAll(mData2);
            }

            ZQUserInfo infoTmp2 = new ZQUserInfo();
            infoTmp2.setCurType(2);
            infoTmp2.setProcessStatus("2");
            infoTmp2.setShowListFlag(type == 2 ? show : false);
            infoTmp2.setGroupnum(Integer.parseInt(arrayNum2));
            mData.add(infoTmp2);
            if (type == 2 && show) {
                mData.addAll(mData3);
            }
        }

        ZQUserInfo infoTmp3 = new ZQUserInfo();
        infoTmp3.setCurType(2);
        infoTmp3.setProcessStatus("3");
        infoTmp3.setShowListFlag(type==3?show:false);
        infoTmp3.setGroupnum(Integer.parseInt(arrayNum3));
        mData.add(infoTmp3);
        if(type==3 && show)
        {
            mData.addAll(mData4);
        }

        ZQUserInfo infoTmp4 = new ZQUserInfo();
        infoTmp4.setCurType(2);
        infoTmp4.setProcessStatus("4");
        infoTmp4.setShowListFlag(type==4?show:false);
        infoTmp4.setGroupnum(Integer.parseInt(arrayNum4));
        mData.add(infoTmp4);
        if(type==4 && show)
        {

            mData.addAll(mData5);
        }

        try {
            mAdapter.notifyDataSetChanged();
        }catch ( Exception ex)
        {
            ex.printStackTrace();
        }
    }
    @Override
    public boolean onRVItemLongClick(ViewGroup parent, View itemView, int position) {
//        Toast.makeText(getActivity(), "长按了条目 " + mAdapter.getItem(position).getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }

    public void getMoreData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
//        shapeLoadingDialog.setLoadingText("加载中...");
//        shapeLoadingDialog.setCanceledOnTouchOutside(false);
//        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        String title = law_searchtxt.getText().toString();

        int pageNo = 1;
        switch (curProcess)
        {
            case 0:
                pageNo =  page1 +1;
                break;
            case 1:
                pageNo =  page2 +1;
                break;
            case 2:
                pageNo =  page3 +1;
                break;
            case 3:
                pageNo =  page4 +1;
                break;
            case 4:
                pageNo =  page5 +1;
                break;


        }
        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("projectId",mProID)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("creditorName","")
                .add("process",curProcess+"")
                .add("pageNo",pageNo+"")
                .add("pageSize","5")
                .build();

        String url = Consts.WEBURL_CONFIRMEDLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
//                runOnUiThread(new Runnable(){
//
//                    @Override
//                    public void run() {
//                        //更新UI
//                        Toast.makeText(PersonSettingOrgActivity.this,"保存失败",Toast.LENGTH_SHORT).show();
//
//                    }
//
//                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

//                shapeLoadingDialog.dismiss();


                String str = response.body().string();

                try{

//                    LawListInfo model = new LawListInfo();
////                                model.setId(data.getString("id"));
//                    model.setTitle("title");
//                    model.setContent("fileName");
//                    mData.add(model);
//                    getActivity().runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            //更新UI
//                            mAdapter.notifyDataSetChanged();
//
//                        }
//
//                    });

                    JSONObject object = new JSONObject(str);
                    mData.clear();
                    if(object.optInt("code") == 0)
                    {
                        JSONObject dataobj = object.getJSONObject("data");
//                        JSONObject groupListobj = dataobj.getJSONObject("list");


                        JSONObject dataobj0 = dataobj.getJSONObject(curProcess+"");

//                        ZQUserInfo[] array0 = new ZQUserInfo[];
                        ZQUserInfo[] array0  = new Gson().fromJson(dataobj0.optString("list"),ZQUserInfo[].class);


                        ArrayList<ZQUserInfo> tmp = new ArrayList<>();
                        switch (curProcess)
                        {
                            case  0:
                                page1++;
                                tmp =  new ArrayList<ZQUserInfo>(Arrays.asList(array0));
                                mData1.addAll(tmp);
                                break;
                            case  1:
                                page2++;
                                tmp =  new ArrayList<ZQUserInfo>(Arrays.asList(array0));
                                mData2.addAll(tmp);
                                break;
                            case  2:
                                page3++;
                                tmp =  new ArrayList<ZQUserInfo>(Arrays.asList(array0));
                                mData3.addAll(tmp);
                                break;
                            case  3:
                                page4++;
                                tmp =  new ArrayList<ZQUserInfo>(Arrays.asList(array0));
                                mData4.addAll(tmp);
                                break;

                            case  4:
                                page5++;
                                tmp =  new ArrayList<ZQUserInfo>(Arrays.asList(array0));
                                mData5.addAll(tmp);
                                break;
                        }
//                        tmp =  new ArrayList<ZQUserInfo>(Arrays.asList(array0));

//                        mData1 = new ArrayList<ZQUserInfo>(Arrays.asList(array0));
//                        mData2 = new ArrayList<ZQUserInfo>(Arrays.asList(array01));
//                        mData3 = new ArrayList<ZQUserInfo>(Arrays.asList(array02));
//                        mData4 = new ArrayList<ZQUserInfo>(Arrays.asList(array03));
//                        mData5 = new ArrayList<ZQUserInfo>(Arrays.asList(array04));

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showList(curProcess,true);
//                                mAdapter.notifyDataSetChanged();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
//                    runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            //更新UI
//                            Toast.makeText(PersonSettingOrgActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
//
//                        }
//
//                    });
                }
            }
        });
    }


    public void getData()
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");


       final  String title = law_searchtxt.getText().toString();

       String  filterSelf = "false";
       String process ="0,1,2,3,4";
       if("false".equalsIgnoreCase(managerFlag))
       {
           filterSelf = "true";
           process ="3,4";
       }else{
           filterSelf = "false";
           process ="0,1,2,3,4";
       }

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("projectId",mProID)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken", userToken)
                .add("creditorName",title)
                .add("process",process)
                .add("pageNo","1")
                .add("pageSize","10")
                .add("filterSelf",filterSelf)
                .build();

        String url = Consts.WEBURL_CONFIRMEDLIST;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
//                runOnUiThread(new Runnable(){
//
//                    @Override
//                    public void run() {
//                        //更新UI
//                        Toast.makeText(PersonSettingOrgActivity.this,"保存失败",Toast.LENGTH_SHORT).show();
//
//                    }
//
//                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                shapeLoadingDialog.dismiss();


                String str = response.body().string();

                try{

                    final JSONObject object = new JSONObject(str);
                    mData.clear();
                    if(object.optInt("code") == 0)
                    {
                        JSONObject dataobj = object.getJSONObject("data");
                        mAuthBaseInfo= new Gson().fromJson(object.getJSONObject("data").getJSONObject("auth").toString(), ZQUserDetailAuthBaseInfo.class);
//                        mAuthBaseInfo.setContactCreditor(false);
//                        mAuthBaseInfo.setDeleteCreditor(false);
                        mAdapter.setAuth(mAuthBaseInfo);
//                        JSONObject groupListobj = dataobj.getJSONObject("list");
                        JSONObject dataobj0 = dataobj.getJSONObject("0");
                        JSONObject dataobj1 = dataobj.getJSONObject("1");
                        JSONObject dataobj2 = dataobj.getJSONObject("2");
                        JSONObject dataobj3 = dataobj.getJSONObject("3");
                        JSONObject dataobj4 = dataobj.getJSONObject("4");
//                        ZQUserInfo[] array0 = new ZQUserInfo[];

                        ZQUserInfo[] array0  = new Gson().fromJson(dataobj0.optString("list"),ZQUserInfo[].class);
                        ZQUserInfo[] array01 = new Gson().fromJson(dataobj1.optString("list"),ZQUserInfo[].class);
                        ZQUserInfo[] array02 = new Gson().fromJson(dataobj2.optString("list"),ZQUserInfo[].class);
                        ZQUserInfo[] array03 = new Gson().fromJson(dataobj3.optString("list"),ZQUserInfo[].class);
                        ZQUserInfo[] array04 = new Gson().fromJson(dataobj4.optString("list"),ZQUserInfo[].class);


                         arrayNum0 = dataobj0.optString("totalCount");
                         arrayNum1 = dataobj1.optString("totalCount");
                         arrayNum2 = dataobj2.optString("totalCount");
                         arrayNum3 = dataobj3.optString("totalCount");
                         arrayNum4 = dataobj4.optString("totalCount");

                        mData1.clear();
                        mData2.clear();
                        mData3.clear();
                        mData4.clear();
                        mData5.clear();

                        if( array0.length == 0 && array01.length == 0 && array02.length == 0
                                && array03.length == 0 && array04.length == 0 &&  "".equalsIgnoreCase(title)) {
                            getActivity().runOnUiThread(new Runnable() {

                                @Override
                                public void run() {
                                    //更新UI

                                    ((ZQUserListActivity)getActivity()).menuShow(false);
                                    ll_nodata.setVisibility(View.VISIBLE);
                                    ll_total.setVisibility(View.INVISIBLE);
                                    mDataRv.setVisibility(View.GONE);
                                    rl_search.setVisibility(View.INVISIBLE);
                                    if(mAuthBaseInfo.isAddCreditor()) {
                                        btn_add_zq.setVisibility(View.VISIBLE);
                                    }else{
                                        btn_add_zq.setVisibility(View.GONE);
                                    }
                                }

                            });
                            return;
                        }

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                ((ZQUserListActivity)getActivity()).menuShow(true);
                                mDataRv.setVisibility(View.VISIBLE);
                                ll_nodata.setVisibility(View.GONE);

                                long total = 0l;
                                if("true".equalsIgnoreCase(managerFlag)) {
                                    total = Long.parseLong(arrayNum0) + Long.parseLong(arrayNum1) +
                                            Long.parseLong(arrayNum2) + Long.parseLong(arrayNum3) +
                                            Long.parseLong(arrayNum4);
                                }else{
                                    total =  Long.parseLong(arrayNum3) +
                                            Long.parseLong(arrayNum4);
                                }
                                tv_total.setText("共计："+total +"人");
                                ll_total.setVisibility(View.VISIBLE);
                                rl_search.setVisibility(View.VISIBLE);
                            }

                        });

                        if("true".equalsIgnoreCase(managerFlag)) {
                            mData1 = new ArrayList<ZQUserInfo>(Arrays.asList(array0));
                            mData2 = new ArrayList<ZQUserInfo>(Arrays.asList(array01));
                            mData3 = new ArrayList<ZQUserInfo>(Arrays.asList(array02));
                        }
                        mData4 = new ArrayList<ZQUserInfo>(Arrays.asList(array03));
                        mData5 = new ArrayList<ZQUserInfo>(Arrays.asList(array04));

                        page1 = 1;
                        page2 = 1;
                        page3 = 1;
                        page4 = 1;
                        page5 = 1;

                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                showList(0,true);
//                                mAdapter.notifyDataSetChanged();

                            }

                        });

                    }else{
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(getActivity(), "失败"+object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });
                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
//                    runOnUiThread(new Runnable() {
//
//                        @Override
//                        public void run() {
//                            //更新UI
//                            Toast.makeText(PersonSettingOrgActivity.this, "保存失败", Toast.LENGTH_SHORT).show();
//
//                        }
//
//                    });
                }
            }
        });
    }


    public void mailNoticeDone(String creditorId)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId",mProID)
                .add("creditorId", creditorId)
                .build();

        String url = Consts.WEBURL_MAILNOTICEDONE;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    JSONObject object = new JSONObject(str);

                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
                                getData();
                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                Toast.makeText(getActivity(), "保存失败"+object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    public void addUser(String groupId,String name,String phone)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("projectId", mProID)
                .add("groupId", groupId)
                .add("memberName", name)
                .add("memberMobile", phone)
                .build();

        String url = Consts.WEBURL_ADDMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"保存失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();
                for (int i = 0; i < headers.size(); i++) {
                    Log.d(TAG, headers.name(i) + ":" + headers.value(i));
                }


                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                Toast.makeText(getActivity(), "保存成功", Toast.LENGTH_SHORT).show();
                                if(createUserDialog != null)
                                {
                                    createUserDialog.dismiss();
                                }
                                ZQUserListActivity activity= (ZQUserListActivity) getActivity();
                                activity.flashMenu();
                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                if("该成员已经添加到该组,请勿重复添加".equalsIgnoreCase(object.optString("msg")))
                                {
                                    createUserDialog.tv_have_user.setVisibility(View.VISIBLE);
                                }
                                Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "保存失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

    public void delUser(String creditorId)
    {
        if(BankruptcyApp.tokeninfo == null|| BankruptcyApp.tokeninfo.getToken() == null)
        {
            return;
        }
        shapeLoadingDialog.setLoadingText("加载中...");
        shapeLoadingDialog.setCanceledOnTouchOutside(false);
        shapeLoadingDialog.show();
        OkHttpClient okHttpClient = new OkHttpClient();
//        HashMap<String, String> params = new HashMap<String, String>();
        Random random = new Random();
        String rom = random.nextLong()+"";
        String timestamp =System.currentTimeMillis()+"";
        String userToken = SPUtils.getInstance(Consts.SPNAME).getString("userToken","");
        String userId = SPUtils.getInstance(Consts.SPNAME).getString("userId","");

        RequestBody requestBody = new FormBody.Builder()
                .add("appid","1000000001")
                .add("nonce",rom)
                .add("timestamp", timestamp)
                .add("token", BankruptcyApp.tokeninfo.getToken())
                .add("userToken",userToken)


                .add("creditorId", creditorId)
                .build();

        String url = Consts.WEBURL_DELMEMBER;
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                shapeLoadingDialog.dismiss();
//                Log.d(TAG, "onFailure: " + e.getMessage());
                getActivity().runOnUiThread(new Runnable(){

                    @Override
                    public void run() {
                        //更新UI
                        Toast.makeText(getActivity(),"操作失败",Toast.LENGTH_SHORT).show();

                    }

                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                shapeLoadingDialog.dismiss();


                String str = response.body().string();
                try{
                    final JSONObject object = new JSONObject(str);
                    if(object.optInt("code") == 0)
                    {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI
                                getData();
                                ((ZQUserListActivity)getActivity()).flashMenu();
                                Toast.makeText(getActivity(), "操作成功", Toast.LENGTH_SHORT).show();
                                if(createUserDialog != null)
                                {

                                    createUserDialog.dismiss();
                                }
                            }

                        });
//                        finish();

                    }else {
                        getActivity().runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
                                //更新UI

                                Toast.makeText(getActivity(), "操作失败"+object.optString("msg"), Toast.LENGTH_SHORT).show();

                            }

                        });

                    }
                    str = "";
                }catch (Exception ex)
                {
                    ex.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            //更新UI
                            Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();

                        }

                    });
                }
            }
        });
    }

}
